package cn.iocoder.yudao.position.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.hires.mapper.ResumeIntentionMapper;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.position.entity.PositionDO;
import cn.iocoder.yudao.position.mapper.PositionMapper;
import cn.iocoder.yudao.position.service.PositionService;
import cn.iocoder.yudao.position.vo.PositionPageReqVO;
import cn.iocoder.yudao.position.vo.PositionSaveReqVO;
import cn.iocoder.yudao.position.vo.PostTionShortVo;
import cn.iocoder.yudao.position.vo.TentSponseVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.POSITION_NOT_EXISTS;


/**
 * 职位-信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class PositionServiceImpl implements PositionService {

    @Resource
    TenantService tenantService;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private ResumeIntentionMapper intentionMapper;


    @Override
    public Long create(PositionSaveReqVO createReqVO) {
        // 插入
        PositionDO positionDO = BeanUtils.toBean(createReqVO, PositionDO.class);
        positionDO.setTenantId(createReqVO.getTenantId());
        System.err.println("---新添加的租户id为：" + positionDO.getTenantId());
        positionDO.setTitle(createReqVO.getPositionCategoryName());

        Long userId = WebFrameworkUtils.getLoginUserId();
        AdminUserDO user = adminUserService.getUser(userId);
        positionDO.setCreator(user.getNickname());
        positionDO.setContactEmail(user.getEmail());
        positionDO.setContactPhone(user.getMobile());
        String roleName = userRoleMapper.getRoleName(userId);
        positionDO.setContactPosition(roleName);
        positionMapper.insert(positionDO);
        // 返回
        return positionDO.getId();
    }

    @Override
    public void update(PositionSaveReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        PositionDO updateObj = BeanUtils.toBean(updateReqVO, PositionDO.class);
        positionMapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        positionMapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (positionMapper.selectById(id) == null) {
            throw exception(POSITION_NOT_EXISTS);
        }
    }

    @Override
    public PositionDO get(Long id) {
        PositionDO positionDO = positionMapper.selectById(id);
        AdminUserDO userByTentId = adminUserService.getUserByTentId(positionDO.getTenantId());
        if (BeanUtil.isNotEmpty(userByTentId)) {
            positionDO.setAdminUserDO(userByTentId);
        }
        Long tenantId = positionDO.getTenantId();
        TenantDO tenant = tenantService.getTenant(tenantId);

        if (BeanUtil.isNotEmpty(tenant)) {
            positionDO.setTenantDO(tenant);
        }
        // 调用im 获取用户状态 todo
        return positionDO;
    }

    @Override
    public PageResult<PositionDO> getPage(PositionPageReqVO pageReqVO) {
        return positionMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PositionDO> getList(PositionPageReqVO pageReqVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();

        PositionDO bean = BeanUtils.toBean(pageReqVO, PositionDO.class);
        LambdaQueryWrapper<PositionDO> positionDOLambdaQueryWrapper = new LambdaQueryWrapper<>(bean);
        if (StrUtil.isNotBlank(pageReqVO.getTitle())) {
            positionDOLambdaQueryWrapper.like(PositionDO::getTitle, pageReqVO.getTitle());
        }
        if (StrUtil.isNotBlank(pageReqVO.getPositionCategoryName())) {
            positionDOLambdaQueryWrapper.like(PositionDO::getPositionCategoryName, pageReqVO.getPositionCategoryName());
        }
        List<String> intentionIds = intentionMapper.getIntentionIds(loginUserId);
        if (CollectionUtils.isNotEmpty(intentionIds)) {
            positionDOLambdaQueryWrapper.in(PositionDO::getPositionCategoryId, intentionIds);
        }
        if (StrUtil.isNotBlank(pageReqVO.getIsLatest())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getIsLatest, pageReqVO.getIsLatest());
        }
        if (StrUtil.isNotBlank(pageReqVO.getIsUrgent())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getIsUrgent, pageReqVO.getIsUrgent());
        }
        if (StrUtil.isNotBlank(pageReqVO.getIsRecommend())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getIsRecommend, pageReqVO.getIsRecommend());
        }

        if (ObjectUtil.isNotEmpty(pageReqVO.getPositionCategoryId())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getPositionCategoryId, pageReqVO.getPositionCategoryId());
        }
        if (ObjectUtil.isNotEmpty(pageReqVO.getExperienceDictCode())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getExperienceDictCode, pageReqVO.getExperienceDictCode());
        }
        if (ObjectUtil.isNotEmpty(pageReqVO.getSalaryDictCode())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getSalaryDictCode, pageReqVO.getSalaryDictCode());
        }
        if (ObjectUtil.isNotEmpty(pageReqVO.getWorkDistrictCode())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getWorkDistrictCode, pageReqVO.getWorkDistrictCode());
        }
        if (ObjectUtil.isNotEmpty(pageReqVO.getEducationDictCode())) {
            positionDOLambdaQueryWrapper.eq(PositionDO::getEducationDictCode, pageReqVO.getEducationDictCode());
        }

        List<PositionDO> positionDOS = positionMapper.selectList(positionDOLambdaQueryWrapper);
        positionDOS.forEach(positionDO -> {
            TenantDO tenant = tenantService.getTenant(positionDO.getTenantId());
            if (BeanUtil.isNotEmpty(tenant)) {
                positionDO.setTenantDO(tenant);
            }
            AdminUserDO userByTentId = adminUserService.getUserByTentId(positionDO.getTenantId());
            if (BeanUtil.isNotEmpty(userByTentId)) {
                positionDO.setAdminUserDO(userByTentId);
            }
        });
        return positionDOS;
    }

    @Override
    public List<TentSponseVo> getTentantList(TenantRespVO tenantRespVO) {
        List<TenantDO> tenantIdList = tenantService.getTenantList(tenantRespVO);
        List<TentSponseVo> tentSponseVos = new ArrayList<>();
        if (CollUtil.isNotEmpty(tenantIdList)) {
            tenantIdList.forEach(tenant -> {
                List<PositionDO> positionDOS = positionMapper.selectList(new LambdaQueryWrapper<PositionDO>().eq(PositionDO::getTenantId, tenant.getId()));
                if (CollUtil.isNotEmpty(positionDOS)) {
                    // 创建响应对象并拷贝属性
                    TentSponseVo tentSponseVo = new TentSponseVo();
                    BeanUtils.copyProperties(tenant, tentSponseVo); // 注意参数顺序根据具体 BeanUtils 实现调整
                    tentSponseVo.setPositionDOS(positionDOS);
                    tentSponseVo.setNum(positionDOS.size());
                    tentSponseVos.add(tentSponseVo);
                }
            });
        }
        return tentSponseVos;
    }

    @Override
    public List<PostTionShortVo> getPositionsByTenantId(Long tenantId) {
        List<PostTionShortVo> postTionShortVos = new ArrayList<>();
        List<PositionDO> positionDOS = positionMapper.selectList(new LambdaQueryWrapper<PositionDO>().eq(PositionDO::getTenantId, tenantId).eq(PositionDO::getStatus, 0));
        positionDOS.forEach(item -> {
            PostTionShortVo postTionShortVo = new PostTionShortVo();
            postTionShortVo.setCategoryId(Math.toIntExact(item.getPositionCategoryId()));
            postTionShortVo.setCategoryName(item.getPositionCategoryName());
            postTionShortVos.add(postTionShortVo);
        });
        return postTionShortVos;
    }

    /**
     * 查询职位id  获取职位的行业字典值
     *
     * @param positionId 行业id
     * @return 获取职位的字典值
     */
    @Override
    public PostTionShortVo getCategory(Long positionId) {
        PositionDO positionDO = get(positionId);
        return new PostTionShortVo(positionDO.getPositionCategoryId(), positionDO.getPositionCategoryName());
    }


}